import { useEffect, useRef } from "react";
import * as echarts from "echarts/core";
import { PieChart, LineChart } from "echarts/charts";
import {
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import { LabelLayout, UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
import type { ECOption } from "../types";

echarts.use([
  PieChart,
  LineChart,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
]);

interface BaseEChartProps {
  option: ECOption;
  width?: string;
  height?: string;
}

const BaseEChart: React.FC<BaseEChartProps> = ({
  option,
  width = "100%",
  height = "360px",
}) => {
  const echartRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const echartInstance = echarts.init(echartRef.current);
    echartInstance.setOption(option);
    window.addEventListener("resize", () => {
      echartInstance.resize();
    });
  }, []);
  return (
    <>
      <div ref={echartRef} style={{ width, height }}></div>
    </>
  );
};

export default BaseEChart;
